﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using JBeamLibrary;

namespace DriveBeamEditor.Controls.BeamNG.Controls
{
    public partial class VehicleControl : UserControl
    {
        #region Fields

        private Vehicle _vehicle;

        public event EventHandler VehicleChanged;

        #endregion

        #region Properties

        public Vehicle Vehicle
        {
            get { return _vehicle; }
            set
            {
                if (_vehicle == value) return;
                _vehicle = value;
                OnVehicleChanged();
            }
        }

        protected BindingSource VehicleSource
        {
            get { return vehicleSource; }
        }

        public Icon Icon
        {
            get;
            set;
        }

        #endregion

        #region CTORs

        public VehicleControl()
        {
            InitializeComponent();
        }

        #endregion

        #region Events

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            UpdateUI();
        }

        #endregion

        #region Methods

        protected virtual void BindVehicle()
        {
            if (Vehicle == null) return;

            vehicleSource.DataSource = Vehicle;
            vehicleSource.ResetBindings(true);
        }

        public virtual void UpdateUI(Control parent = null)
        {
            if (parent == null) parent = this;
            foreach (var control in parent.Controls.Cast<Control>())
            {
                if (control is TextBox || control is Label || control is Button) control.Enabled = Vehicle != null;
                else UpdateUI(control);
            }
        }

        protected virtual void OnVehicleChanged()
        {
            BindVehicle();
            UpdateUI();

            if (VehicleChanged != null)
                VehicleChanged(this, new EventArgs());
        }

        #endregion
    }
}
